package lastcontrnt.memoryleak;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class Leak6 {
    /**
     * 假设该对象实例变量a,d是关键域
     * a,d分别相等的对象逻辑相等
     */
    private int a;
    private double d;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Leak6 that = (Leak6) o;
        return a == that.a &&
                Double.compare(that.d, d) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(a, d);
    }

    public Leak6(int a, double d) {
        this.a = a;
        this.d = d;
    }

    public Leak6() {
    }

    @Override
    public String toString() {
        return "HashCodeTest{" +
                "a=" + a +
                ", d=" + d +
                '}';
    }

    public static void main(String[] args) {
        HashMap<Leak6, Integer> map = new HashMap<>();
        Leak6 h1 = new Leak6(1, 1);
        map.put(h1, 100);
        Leak6 h2 = new Leak6(2, 2);
        map.put(h2, 100);

        //修改关键域 导致改变哈希值
        h1.a=2;
        System.out.println(map.remove(h1));//null
        Set<Map.Entry<Leak6, Integer>> entrySet = map.entrySet();
        for (Map.Entry<Leak6, Integer> entry : entrySet) {
            System.out.println(entry);
        }

        map.put(h1,100);
        map.put(new Leak6(1, 1), 100);
        //map.size()=?
        int i=0;
        System.out.println(map.size());
        //HashCodeTest{a=100, d=1.5}=100
        //HashCodeTest{a=2, d=2.5}=200
    }
}